/*	Copyright 2013 RangerUFO
 *
 *	This file is part of Libevent-helper.
 *
 *	Libevent-helper is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Lesser General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	Libevent-helper is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Lesser General Public License for more details.
 *
 *	You should have received a copy of the GNU Lesser General Public License
 *	along with Libevent-helper.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <event2/helper.h>
#include <event2/acceptor.h>
#include <event2/session.h>
#include <stdio.h>

void read_cb(struct evsession* s, void* args)
{
	evsession_write_buffer(s, evsession_get_input(s));
}

void event_cb(struct evsession* s, short what, void* args)
{
	if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
	{
		printf("%s:%d disconnect.\n", evsession_get_peer_ip(s), evsession_get_peer_port(s));
		fflush(stdout);
		evsession_free(s);
	}
}

void accept_cb(struct evacceptor* ac, struct evsession* s, void* args)
{
	printf("%s:%d connect.\n", evsession_get_peer_ip(s), evsession_get_peer_port(s));
	fflush(stdout);
	evsession_setcb(s, read_cb, 0, event_cb, 0);
}

void accept_error_cb(struct evacceptor* ac, void* args)
{
	puts("Error from accept() call.");
	fflush(stdout);
}

int main()
{
	if (evhelper_init() == -1)
	{
		puts("Init evhelper failed.");
		return -1;
	}

	struct event_base* base = event_base_new();

	if (!base)
	{
		puts("Create event_base failed.");
		return -1;
	}

	struct evacceptor* ac = evacceptor_new_bind(base, 0, 53000, -1);

	if (!ac)
	{
		puts("Create evacceptor failed.");
		event_base_free(base);
		return -1;
	}

	evacceptor_setcb(ac, accept_cb, accept_error_cb, 0);

	int ret = event_base_dispatch(base);

	evacceptor_free(ac);
	event_base_free(base);
	
	return ret;
}
